package tmt.usercenter.web.bean;


import com.tmt.helper.ReflectHelper;

import java.util.HashMap;
import java.util.Map;

public class TmtSemaphore {

    public static final Map<String, TmtSemaphore> LocalSemaphoreMap = new HashMap<>();

    private Object semaphore;

    private Integer ownerThread = null;

    private int referCount = 0;

    private String name;

    public TmtSemaphore(String name, Object semaphore){
        this.name = name;
        this.semaphore = semaphore;
    }

    public void acquire(){
        if (ownerThread == null || ownerThread != Thread.currentThread().hashCode()) {
            ReflectHelper.invokeMethod(semaphore, "acquire", null, null);
            ownerThread = Thread.currentThread().hashCode();
        }
        referCount++;
    }

    public void release(){
        if (ownerThread == Thread.currentThread().hashCode()){
            referCount--;
            if (referCount <= 0) {
                ownerThread = null;
                referCount = 0;
                ReflectHelper.invokeMethod(semaphore, "release", null, null);
                synchronized (LocalSemaphoreMap){
                    LocalSemaphoreMap.remove(name);
                }
            }
        }
    }
}